package com.pms.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.pms.domain.FTPSettings;
import com.pms.domain.HdBatch;
import com.pms.domain.HdDailyLoan;
import com.pms.domain.HdMonthlyRepayment;
import com.pms.domain.JobConfig;
import com.pms.exception.AppException;
import com.pms.service.FTPSettingsService;
import com.pms.service.HdBatchService;
import com.pms.service.HdDailyLoanService;
import com.pms.service.HdMonthlyRepaymentService;
import com.pms.service.HdReportService;
import com.pms.utils.FtpTools;

@Component
public class HdReportServiceImpl implements HdReportService {
	
	public static Logger logger = Logger.getLogger(HdReportServiceImpl.class);
	
	public static final String DELIMITER = ",";
	
	@Autowired
	HdBatchService hdBatchService;
	
	@Autowired
	HdDailyLoanService hdDailyLoanService;
	
	@Autowired
	HdMonthlyRepaymentService hdMonthlyRepaymentService;
	
	@Autowired
	FTPSettingsService fTPSettingsService;

	@Override
	public void hdHandler(JobConfig cfg) {
		Date current = new Date();
		logger.info("*********" + current.toString() + "::jobcfg_id=" + cfg.getJobcfgid() + "定时任务开始执行*********");
		FTPSettings settings = fTPSettingsService.selectFTPSettingsById(cfg.getJobcfgid());
		if (settings != null) {
			List<String> list = listAllFile(settings);
			for (String fileName : list) {
				String checkFile = fileName.substring(0,fileName.indexOf(".")) + settings.getCheckfilesuffix();
				try {
					FtpTools.downFile(settings.getFtpserver(), settings.getFtpport(), settings.getFtpuser(),
							settings.getFtppassword(), settings.getRemotepath(), checkFile, fileName,
							settings.getLocalftppath());
					handleFile(fileName, settings.getTexfileencodeing(), settings.getLocalftppath(), cfg.getProjectid());

				} catch (NumberFormatException | AppException e) {
					logger.info(e.getMessage());
				}
			}
		}
		current = new Date();
		logger.info("*********" + current.toString() + "::jobcfg_id=" + cfg.getJobcfgid() + "定时任务执行结束*********");
	}
	
	private List<String> listAllFile(FTPSettings settings) {
		List<String> list = null;
		try {
			list = FtpTools.listAllDatFile(settings.getFtpserver(), settings.getFtpport(), settings.getFtpuser(),
					settings.getFtppassword(), settings.getRemotepath(), settings.getCheckfilesuffix());
		} catch (NumberFormatException | AppException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	private void handleFile(String fileName, String textFileEncodeing, String localFTPPath, Integer projectId) {
		
		int index = fileName.indexOf(".");
		String fileNameShort = fileName.substring(0, index);
		String fileSuffix = fileName.substring(index); 
		HdBatch batch = new HdBatch();
		String delimiter;
		Integer batchid;
		// 验证文件是否为空，若为空则不执行插入操作
		if (fileNameShort.startsWith("daily") || fileNameShort.startsWith("monthly")) {
			String fileFullName = getFileFullName(fileName, localFTPPath);
			File file = new File(fileFullName);
			try {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
				@SuppressWarnings("resource")
				BufferedReader bufferedReader = new BufferedReader(read);
				if(bufferedReader.readLine() != null){
					String[] fields = fileNameShort.split("_");
					if (fields.length == 3) {
						batch.setBatchperiod(fields[0]);
						batch.setBatchtype(fields[1]);
						batch.setBatchdate(fields[2]);
						batch.setFileName(fileName);
						batch.setProjectid(projectId);
						
						int state = 1;
						batch.setBatchstate(state);
						delimiter = DELIMITER;
						hdBatchService.insertHdBatch(batch);
						batchid = batch.getBatchid();
						
						if (fileName.startsWith("daily")) {
							state = handleFileContentDaily(fileName, delimiter, fileSuffix,batchid,textFileEncodeing,localFTPPath);
						}else if(fileName.startsWith("monthly")){
							state = handleFileContentMonthly(fileName, delimiter,fileSuffix, batchid,textFileEncodeing,localFTPPath);
						}
						batch.setBatchstate(state);
						hdBatchService.updateHdBatch(batch);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else{
			logger.error(fileName + "文件名格式错误！");
		}
	}
	
	private int handleFileContentDaily(String fileName, String delimiter,String fileSuffix, Integer batchid,String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<HdDailyLoan> hdDailyLoans = new ArrayList<HdDailyLoan>();
		String fileFullName = getFileFullName(fileName,localFTPPath);
		
		if (!(".dat".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}
		File file = new File(fileFullName);
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count >= 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 14) {
						HdDailyLoan hdDailyLoan = new HdDailyLoan();
						hdDailyLoan.setBatchid(batchid);
						hdDailyLoan.setStatisticsDay(fields[0]);
						hdDailyLoan.setPartner(fields[1]);
						hdDailyLoan.setBusinessNo(fields[2]);
						hdDailyLoan.setApplyNo(fields[3]);
						hdDailyLoan.setName(fields[4]);
						hdDailyLoan.setIdNumber(fields[5]);
						hdDailyLoan.setApplyDate(stringToDate(fields[6]));
						hdDailyLoan.setFinalApprovalDate(stringToDate(fields[7]));
						hdDailyLoan.setPayforState(fields[8]);
						hdDailyLoan.setPayforDate(stringToDate(fields[9]));
						hdDailyLoan.setApplyLoanAmount(Double.parseDouble(fields[10]));
						hdDailyLoan.setPayforAmount(Double.parseDouble(fields[11]));
						hdDailyLoan.setPeriodNumber(fields[12]);
						hdDailyLoan.setPeriodRates(Double.parseDouble(fields[13]));
						hdDailyLoan.setFileName(fileName);
						hdDailyLoans.add(hdDailyLoan);
					}
				}
				count++;
			}
			// 批量插入
			hdDailyLoanService.insertHdDailyLoan(hdDailyLoans);
			result = 2;
			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}
	
	private int handleFileContentMonthly(String fileName, String delimiter, String fileSuffix, Integer batchid,String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<HdMonthlyRepayment> hdMonthlyRepayments = new ArrayList<HdMonthlyRepayment>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".dat".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}
		
		File file = new File(fileFullName);
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count >= 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 34) {
						HdMonthlyRepayment hdMonthlyRepayment = new HdMonthlyRepayment();
						hdMonthlyRepayment.setBatchid(batchid);
						hdMonthlyRepayment.setStatisticsMonth(fields[0]);
						hdMonthlyRepayment.setApplyNo(fields[1]);
						hdMonthlyRepayment.setPartner(fields[2]);
						hdMonthlyRepayment.setBusinessNo(fields[3]);
						hdMonthlyRepayment.setName(fields[4]);
						hdMonthlyRepayment.setIdNumber(fields[5]);
						hdMonthlyRepayment.setApplyDate(stringToDate(fields[6]));
						hdMonthlyRepayment.setFinalApprovalDate(stringToDate(fields[7]));
						hdMonthlyRepayment.setPayforDate(stringToDate(fields[8]));
						hdMonthlyRepayment.setRepayStartDate(stringToDate(fields[9]));
						hdMonthlyRepayment.setRepayEndDate(stringToDate(fields[10]));
						hdMonthlyRepayment.setPeriodNumber(Integer.parseInt(fields[11]));
						hdMonthlyRepayment.setApplyAmount(Double.parseDouble(fields[12]));
						hdMonthlyRepayment.setPayforAmount(Double.parseDouble(fields[13]));
						hdMonthlyRepayment.setLoanState(fields[14]);
						hdMonthlyRepayment.setCurrentRepayNum(Integer.parseInt(fields[15]));
						hdMonthlyRepayment.setCurrentRepayAmount(Double.parseDouble(fields[16]));
						hdMonthlyRepayment.setCurrentRepayCapital(Double.parseDouble(fields[17]));
						hdMonthlyRepayment.setCurrentRepayInterest(Double.parseDouble(fields[18]));
						hdMonthlyRepayment.setCurrentOverdueNum(Integer.parseInt(fields[19]));
						hdMonthlyRepayment.setCurrentOverdueAmount(Double.parseDouble(fields[20]));
						hdMonthlyRepayment.setCurrentOverdueCapital(Double.parseDouble(fields[21]));
						hdMonthlyRepayment.setCurrentOverdueInterest(Double.parseDouble(fields[22]));
						hdMonthlyRepayment.setEarlyRepayIsneed(fields[23]);
						hdMonthlyRepayment.setTotalRepayedCapital(Double.parseDouble(fields[24]));
						hdMonthlyRepayment.setTotalRepayedIntetest(Double.parseDouble(fields[25]));
						hdMonthlyRepayment.setTotalRepayedAmount(Double.parseDouble(fields[26]));
						hdMonthlyRepayment.setRemainPeriodNumber(Integer.parseInt(fields[27]));
						hdMonthlyRepayment.setRemainRepayAmount(Double.parseDouble(fields[28]));
						hdMonthlyRepayment.setTotalOverdueCount(Integer.parseInt(fields[29]));
						hdMonthlyRepayment.setTotalOverduePeriodNum(Integer.parseInt(fields[30]));
						hdMonthlyRepayment.setTotalOverdueRepayedAmount(Double.parseDouble(fields[31]));
						hdMonthlyRepayment.setTotalOperatorShareAmount(Double.parseDouble(fields[32]));
						hdMonthlyRepayment.setCurrentOperatorShareAmount(Double.parseDouble(fields[33]));
						hdMonthlyRepayment.setFileName(fileName);
						hdMonthlyRepayments.add(hdMonthlyRepayment);
					}
				}
				count++;
			}
			// 批量插入
			hdMonthlyRepaymentService.insertHdMonthlyRepayment(hdMonthlyRepayments);
			result = 2;
			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}
	
	
	/**
	 * 文件名加上绝对路径
	 * 
	 * @param fileName
	 * @return
	 */
	private String getFileFullName(String fileName, String localFTPPath) {
		StringBuffer buffer = new StringBuffer();
		if (localFTPPath.endsWith("/")) {
			buffer.append(localFTPPath);
			buffer.append(fileName);
		} else {
			buffer.append(localFTPPath);
			buffer.append("/");
			buffer.append(fileName);
		}
		return buffer.toString();
	}

	private Date stringToDate(String s) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(s);
		} catch (ParseException e) {
			// e.printStackTrace();
		}
		return null;
	}
}
